<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>放大镜</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      font-size: 0;
    }

    .box {
      margin: 10px;
      width: 400px;
      height: 400px;
      border: 1px solid #000;
      position: relative;
      cursor: pointer;
      box-sizing: border-box;
    }

    .mask {
      width: 200px;
      height: 200px;
      background-color: aqua;
      opacity: .5;
      position: absolute;
      top: 0;
      left: 0;
      display: none;
    }

    .big {
      position: absolute;
      top: 0;
      left: 410px;
      z-index: 1;
      width: 500px;
      height: 500px;
      border: 1px solid #000;
      overflow: hidden;
      display: none;
      box-sizing: border-box;
    }

    .bigImg {
      width: 1000px;
      height: 1000px;
      position: absolute;
      top: 0;
      left: 0;
    }

    .img {
      width: 100%;
      height: 100%;
    }
  </style>
</head>

<body>
  <div class="box">
    <img src="./image/nidouzi.jpg" class="img" alt="1">
    <div class="mask"></div>
    <div class=big>
      <img src="./image/nidouzi.jpg" class="bigImg" alt="2">
    </div>
  </div>

  <script>
    let box = document.querySelector(".box");
    let mask = document.querySelector(".mask");
    let big = document.querySelector(".big");
    let bigImg = document.querySelector(".bigImg");

    box.addEventListener("mouseover", () => {
      mask.style.display = 'block';
      big.style.display = 'block';
    })

    box.addEventListener("mouseout", () => {
      mask.style.display = '';
      big.style.display = '';
    })

    /*
    mask移动距离x                    大图片移动距离
    mask最大移动距离maskMax          大图片最大移动距离bigMax
    */

    box.addEventListener("mousemove", (ele) => {
      let x = ele.pageX - box.offsetLeft;
      let y = ele.pageY - box.offsetTop;
      let maskMax = box.offsetWidth - mask.offsetWidth;

      //鼠标在mask的中心
      x = x - mask.offsetWidth / 2;
      y = y - mask.offsetHeight / 2;

      //限制mask的范围
      if (x <= 0) {
        x = 0;
      } else if (x > maskMax) {
        x = maskMax;
      }
      if (y <= 0) {
        y = 0;
      } else if (y > maskMax) {
        y = maskMax;
      }

      //mask根据坐标移动的距离
      mask.style.left = `${x}px`;
      mask.style.top = `${y}px`;

      //大图片移动
      let bigMax = bigImg.offsetWidth - big.offsetWidth;
      let bigX = x * bigMax / maskMax;
      let bigY = y * bigMax / maskMax;
      bigImg.style.left = `-${bigX}px`;
      bigImg.style.top = `-${bigY}px`;
    })
  </script>
</body>

</html>